package com.osdp.sc.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.osdp.common.exception.PlatformException;
import com.osdp.common.util.ConvertUtil;
import com.osdp.common.util.MessageUtil;
import com.osdp.sc.dto.TenantUserDTO;
import com.osdp.sc.entity.ScTenantUser;
import com.osdp.sc.mapper.ScTenantUserMapper;
import com.osdp.sc.service.IScTenantUserService;
import com.osdp.sc.vo.ScTenantUserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;

@Service
public class ScTenantUserServiceImpl extends ServiceImpl<ScTenantUserMapper, ScTenantUser> implements IScTenantUserService {

    @Autowired
    private ScTenantUserMapper tenantUserMapper;

    @Override
    public List<ScTenantUserVo> queryTenantUserByUserId(String userId) {
        return tenantUserMapper.queryTenantUserByUserId(userId);
    }

    @Override
    public List<ScTenantUserVo> queryTenantUserByTenanId(String tenantId) {
        return tenantUserMapper.queryTenantUserByTenanId(tenantId);
    }
    //-------------------------用于登录-------------------------//
    @Override
    public List<TenantUserDTO> queryTenantByUserId(String userId) {
        List<ScTenantUserVo> list = queryTenantUserByUserId(userId);
        return ConvertUtil.sourceToTarget(list, TenantUserDTO.class);
    }

    /**
     * 获取与与租户编码一致的租户id
     *
     * @param tenants
     * @param tenantCode
     * @return
     */
    @Override
    public String getCurrentTenantId(List<TenantUserDTO> tenants, String tenantCode) {
        if (CollectionUtils.isEmpty(tenants)) {
            throw new PlatformException(MessageUtil.getMessage(10038,tenantCode));
        }
        Optional<TenantUserDTO> tenantOpt = tenants.stream().filter(t -> StringUtils.equals(tenantCode, t.getTenantCode())).findFirst();
        if (!tenantOpt.isPresent()) {
            throw new PlatformException(MessageUtil.getMessage(10038,tenantCode));
        }
        return tenantOpt.get().getTenantId();
    }

}
